from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,redirect
from django.contrib.auth.hashers import make_password, check_password
from django.urls import reverse
from .. import models
import time,os
from shopmall.settings import BASE_DIR
from django.db.models import Q

from django.core.paginator import Paginator
# 用户列表
def userlist(request):
    userinfo = models.User.objects.all()

    types = request.GET.get('type')
    # 接受关键字
    search = request.GET.get('search')
    # 判断用是否搜索内容
    if types:
        if types=='all':
            userinfo = models.User.objects.filter(Q(uname__contains=search)|Q(uQQ__contains=search)|Q(uphone__contains=search))
        elif types=='name':
            userinfo = models.User.objects.filter(uname__contains=search)
        elif types=='phone':
            userinfo = models.User.objects.filter(uphone__contains=search)
        elif types == 'QQ':
            userinfo = models.Users.objects.filter(uQQ__contains=search)
        
     # 实例化分页对象
    p = Paginator(userinfo, 10)

    #一共可以分多少页
    sumpage=p.num_pages


    # 取第几页的数据
     # 接受用户的页码
    page = int(request.GET.get('p',1))
    # 第几页的数据
    page1 = p.page(page)

    # 判断 如果用输入的页码<=3 显示前五个页码
    if page<=3:
        # 页码的迭代序列  [1,2,3,4,5,6,7]
        prange = p.page_range[:5]
    elif page+2>=sumpage:
        prange = p.page_range[-5:]
    else:
        prange = p.page_range[page-3:page+2]

    # 进行数据分配 通过 模板语法将数据展示到模板当中
    return render(request,'myadmin/user/userinfo.html',{'userinfo':page1,'prange':prange,'page':page,'sumpage':sumpage})


def adduser(request):
    #如果是用GET提交,那么返回添加页面
    if request.method=='GET':
        return render(request,'myadmin/user/adduser.html')
    #如果是POST请求
    elif request.method=='POST':
        # 转换字典
        userinfo = request.POST.dict()
        userinfo.pop('csrfmiddlewaretoken')
        myfile = request.FILES.get("uimgurl",None)

        if not myfile:
            return HttpResponse("<script>alert('请选择头像');location.href=''</script>")
        #图片信息           图片信息的处理结果
        userinfo['uimgurl']=upload(myfile)
        userinfo['upwd'] = make_password(userinfo['upwd'],None,'pbkdf2_sha256')
        try:
            
            user = models.User(**userinfo)
            
            user.save()
            return redirect(reverse('myadmin_userlist'))
        except :
            return HttpResponse("<script>alert('添加失败！');location.href=''</script>")

def upload(myfile):
    # 新名字(路径加名字)
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open("./static/myadmin/img/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)
    destination.close()
    # /static/pics/filename
    return '/static/myadmin/img/'+filename


def respwd(request):
    uid = request.GET.get('id')
    userinfo = models.User.objects.get(id = uid)
    userinfo.password = make_password('123456', None, 'pbkdf2_sha256')
    userinfo.save()
    data = {'msg':'重置成功'}
    return JsonResponse(data)

def changes(request):
    uid = request.GET.get('id')
    status = request.GET.get('ustatus')
    try:
        userinfo = models.User.objects.get(id = uid )

        userinfo.ustatus = int(status)
        userinfo.save()

        msg = {'msg':'修改成功'}
        return JsonResponse(msg)
    except:
        msg = {'msg':'修改失败'}

        return JsonResponse(msg)

def deluser(request):
    uid = request.GET.get('uid')
    print('uid',type(uid))
    userinfo = models.User.objects.get(id = uid)
    userinfo.delete()
    return redirect(reverse('myadmin_userlist'))

def edituser(request):
    if request.method == "GET":
        uid = request.GET.get('uid')
        userinfo = models.User.objects.get(id=uid)
        content = {'userinfo':userinfo}
        return render(request,'myadmin/user/edituser.html',content)
    elif request.method == "POST":
        uid = request.GET.get('uid')
        userinfo = models.User.objects.get(id = uid)
        userinfo.uname = request.POST['uname']
        userinfo.upwd = request.POST['upwd']
        userinfo.uphone = request.POST['uphone']
        userinfo.uQQ = request.POST['uQQ']
        userinfo.uemail = request.POST['uemail']
        userinfo.save()
        return redirect(reverse('myadmin_userlist'))